package org.eenie.kdassistant.ui;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yunda.crypt.EDOutputData;
import com.yunda.crypt.NativeEncryption;

import org.eenie.kdassistant.injector.components.AppComponent;
import org.eenie.kdassistant.net.common.CommonApi;
import org.eenie.kdassistant.net.common.ExpressStateListener;
import org.eenie.kdassistant.net.yd_api.YDBaseResponse;
import org.eenie.kdassistant.utils.LogUtil;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Transient;

import java.io.IOException;

import okhttp3.ResponseBody;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Eenie on 2017/8/1.
 * Email: eeniework@gmail.com
 * Des:
 */

@Entity(nameInDb = "express")
public class ExpressEntity {
    @Id(autoincrement = true)
    private Long _id;
    private String src;
    private String express;
    private int type;
    private String state_des = "等待上传";
    private int state;//0 等待上传   1正在上传  2等待确认结果  3上传成功 4上传失败
    private long scan_time;


    private int express_type;//上传的类型   0、签收   1、到件

    @Transient
    private AppComponent mAppComponent;
    @Transient
    private ExpressEntityDao mExpressEntityDao;
    @Transient
    private ExpressStateListener listener;

    public ExpressEntity(String express, int type, long time) {
        this.express = express;
        this.type = type;
        this.scan_time = time;

    }

    public AppComponent getAppComponent() {
        return mAppComponent;
    }

    public void setAppComponent(AppComponent appComponent) {
        mAppComponent = appComponent;
        mExpressEntityDao = mAppComponent.getDaoSession().getExpressEntityDao();
    }


    public ExpressStateListener getListener() {
        return listener;
    }

    public void setListener(ExpressStateListener listener) {
        this.listener = listener;
    }

    @Generated(hash = 2115572612)
    public ExpressEntity(Long _id, String src, String express, int type, String state_des, int state, long scan_time,
            int express_type) {
        this._id = _id;
        this.src = src;
        this.express = express;
        this.type = type;
        this.state_des = state_des;
        this.state = state;
        this.scan_time = scan_time;
        this.express_type = express_type;
    }

    @Generated(hash = 296325710)
    public ExpressEntity() {
    }

    public Long get_id() {
        return this._id;
    }

    public void set_id(Long _id) {
        this._id = _id;
    }

    public String getSrc() {
        return this.src;
    }

    public void setSrc(String src) {
        this.src = src;
    }

    public String getExpress() {
        return this.express;
    }

    public void setExpress(String express) {
        this.express = express;
    }

    public int getType() {
        return this.type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public String getState_des() {
        return this.state_des;
    }

    public void setState_des(String state_des) {
        this.state_des = state_des;
    }

    public int getState() {
        return this.state;
    }

    public void setState(int state) {
        this.state = state;
    }

    public long getScan_time() {
        return this.scan_time;
    }

    public void setScan_time(long scan_time) {
        this.scan_time = scan_time;
    }

    public void upload() {
        if (ExpressEntity.this.getType() == -1) {
            ExpressEntity.this.setState_des("快递公司不明确,请手动选择快递公司。");
            ExpressEntity.this.setState(4);
            mExpressEntityDao.update(ExpressEntity.this);
            listener.onFailure(ExpressEntity.this);
            return;
        }
        CommonApi mCommonApi = mAppComponent.getKdyApi();
        if (ExpressEntity.this.getType() == 0) {
            mCommonApi = mAppComponent.getXzApi();
        } else if (ExpressEntity.this.getType() == 1) {
            mCommonApi = mAppComponent.getZZTApi();
        }

        else if (ExpressEntity.this.getType() == 2) {
            mCommonApi = mAppComponent.getKdyApi();
        }
        else if (ExpressEntity.this.getType() == 3) {
            mCommonApi = mAppComponent.getYDApi();
        }


        ExpressEntity.this.setState_des("正在上传...");
        ExpressEntity.this.setState(1);
        listener.before(ExpressEntity.this);


        if (this.getExpress_type() == 0) {
            mCommonApi.addSignExpress(this.getExpress())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<ResponseBody>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {
                            e.printStackTrace();
                            ExpressEntity.this.setState_des("上传失败");
                            ExpressEntity.this.setState(4);
                            mExpressEntityDao.update(ExpressEntity.this);
                            listener.onFailure(ExpressEntity.this);
                        }

                        @Override
                        public void onNext(ResponseBody responseBody) {
                            try {
                                JSONObject data = JSON.parseObject(responseBody.string());
                                if (ExpressEntity.this.getType() == 0) {
                                    if (data.getInteger("code") != 1000) {
                                        ExpressEntity.this.setState_des(data.getString("prompt"));
                                        ExpressEntity.this.setState(4);
                                        mExpressEntityDao.update(ExpressEntity.this);
                                        listener.onFailure(ExpressEntity.this);
                                    } else {
                                        ExpressEntity.this.setState_des("上传成功");
                                        ExpressEntity.this.setState(3);
                                        mExpressEntityDao.update(ExpressEntity.this);
                                        listener.onSuccess(ExpressEntity.this);
                                    }
                                } else if (ExpressEntity.this.getType() == 1) {
                                    if (data.getBoolean("status")) {
                                        JSONArray resArray = data.getJSONArray("result");
                                        if (resArray.size() > 0) {
                                            JSONObject resObj = resArray.getJSONObject(0);
                                            if (resObj.getBoolean("uploadResult")) {
                                                ExpressEntity.this.setState_des("上传成功");
                                                ExpressEntity.this.setState(3);
                                                mExpressEntityDao.update(ExpressEntity.this);
                                                listener.onSuccess(ExpressEntity.this);
                                            } else {
                                                ExpressEntity.this.setState_des(resObj.getString("message"));
                                                ExpressEntity.this.setState(4);
                                                mExpressEntityDao.update(ExpressEntity.this);
                                                listener.onFailure(ExpressEntity.this);
                                            }
                                        }
                                    } else {
                                        ExpressEntity.this.setState_des(data.getString("message"));
                                        ExpressEntity.this.setState(4);
                                        mExpressEntityDao.update(ExpressEntity.this);
                                        listener.onFailure(ExpressEntity.this);
                                    }
                                } else if (ExpressEntity.this.getType() == 2) {
                                    if (data.getInteger("code") != 0) {
                                        ExpressEntity.this.setState_des(data.getString("msg"));
                                        ExpressEntity.this.setState(4);
                                        mExpressEntityDao.update(ExpressEntity.this);
                                        listener.onFailure(ExpressEntity.this);
                                    } else {


                                        if (!data.getJSONObject("data").getString("status").equals("fail")) {
                                            JSONArray errorNo = data.getJSONObject("data").getJSONObject("result").getJSONArray("error");
                                            for (int i = 0; i < errorNo.size(); i++) {
                                                JSONObject errorRes = errorNo.getJSONObject(i);
                                                if (errorRes.getString("waybillNo").equals(ExpressEntity.this.getExpress())) {
                                                    ExpressEntity.this.setState_des(errorRes.getString("reason"));
                                                    ExpressEntity.this.setState(4);
                                                    mExpressEntityDao.update(ExpressEntity.this);
                                                    listener.onFailure(ExpressEntity.this);
                                                    return;
                                                }
                                            }
                                            ExpressEntity.this.setState_des("上传成功");
                                            ExpressEntity.this.setState(3);
                                            mExpressEntityDao.update(ExpressEntity.this);
                                            listener.onSuccess(ExpressEntity.this);
                                        } else {
                                            ExpressEntity.this.setState_des(data.getJSONObject("data").getString("desc"));
                                            ExpressEntity.this.setState(4);
                                            mExpressEntityDao.update(ExpressEntity.this);
                                            listener.onFailure(ExpressEntity.this);
                                        }




                                    }
                                } else if (ExpressEntity.this.getType() == 3) {
                                    YDBaseResponse response = data.toJavaObject(YDBaseResponse.class);


                                    if (response.getDeEntity().getJSONObject("dta").getString("st").equals("ok")) {
                                        ExpressEntity.this.setState_des("签收上传成功");
                                        ExpressEntity.this.setState(3);
                                        mExpressEntityDao.update(ExpressEntity.this);
                                        listener.onSuccess(ExpressEntity.this);
                                    } else {
                                        ExpressEntity.this.setState_des(response.getDeEntity().getJSONObject("dta").getString("ermsg"));
                                        ExpressEntity.this.setState(4);
                                        mExpressEntityDao.update(ExpressEntity.this);
                                        listener.onFailure(ExpressEntity.this);
                                    }


                                    LogUtil.e("sign res body = " + response.getDecodeBody());


                                }


                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                        }
                    });


        } else {
            mCommonApi.addAcceptExpress(this.getExpress())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<ResponseBody>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {
                            e.printStackTrace();
                            ExpressEntity.this.setState_des("上传失败");
                            ExpressEntity.this.setState(4);
                            mExpressEntityDao.update(ExpressEntity.this);
                            listener.onFailure(ExpressEntity.this);
                        }

                        @Override
                        public void onNext(ResponseBody responseBody) {
                            try {
                                JSONObject data = JSON.parseObject(responseBody.string());
                                if (ExpressEntity.this.getType() == 0) {
                                    if (data.getInteger("code") != 1000) {
                                        ExpressEntity.this.setState_des(data.getString("prompt"));
                                        ExpressEntity.this.setState(4);
                                        mExpressEntityDao.update(ExpressEntity.this);
                                        listener.onFailure(ExpressEntity.this);
                                    } else {
                                        ExpressEntity.this.setState_des("上传成功");
                                        ExpressEntity.this.setState(3);
                                        mExpressEntityDao.update(ExpressEntity.this);
                                        listener.onSuccess(ExpressEntity.this);
                                    }
                                } else if (ExpressEntity.this.getType() == 1) {
                                    if (data.getBoolean("status")) {
                                        JSONArray resArray = data.getJSONArray("result");
                                        if (resArray.size() > 0) {
                                            JSONObject resObj = resArray.getJSONObject(0);
                                            if (resObj.getBoolean("uploadResult")) {
                                                ExpressEntity.this.setState_des("上传成功");
                                                ExpressEntity.this.setState(3);
                                                mExpressEntityDao.update(ExpressEntity.this);
                                                listener.onSuccess(ExpressEntity.this);
                                            } else {
                                                ExpressEntity.this.setState_des(resObj.getString("message"));
                                                ExpressEntity.this.setState(4);
                                                mExpressEntityDao.update(ExpressEntity.this);
                                                listener.onFailure(ExpressEntity.this);
                                            }
                                        }
                                    } else {
                                        ExpressEntity.this.setState_des(data.getString("message"));
                                        ExpressEntity.this.setState(4);
                                        mExpressEntityDao.update(ExpressEntity.this);
                                        listener.onFailure(ExpressEntity.this);
                                    }
                                } else if (ExpressEntity.this.getType() == 2) {
                                    if (data.getInteger("code") != 0) {
                                        ExpressEntity.this.setState_des(data.getString("msg"));
                                        ExpressEntity.this.setState(4);
                                        mExpressEntityDao.update(ExpressEntity.this);
                                        listener.onFailure(ExpressEntity.this);
                                    } else {

                                        if (!data.getJSONObject("data").getString("status").equals("fail")) {
                                            JSONArray errorNo = data.getJSONObject("data").getJSONObject("result").getJSONArray("error");
                                            for (int i = 0; i < errorNo.size(); i++) {
                                                JSONObject errorRes = errorNo.getJSONObject(i);
                                                if (errorRes.getString("waybillNo").equals(ExpressEntity.this.getExpress())) {
                                                    ExpressEntity.this.setState_des(errorRes.getString("reason"));
                                                    ExpressEntity.this.setState(4);
                                                    mExpressEntityDao.update(ExpressEntity.this);
                                                    listener.onFailure(ExpressEntity.this);
                                                    return;
                                                }
                                            }
                                            ExpressEntity.this.setState_des("上传成功");
                                            ExpressEntity.this.setState(3);
                                            mExpressEntityDao.update(ExpressEntity.this);
                                            listener.onSuccess(ExpressEntity.this);
                                        } else {
                                            ExpressEntity.this.setState_des(data.getJSONObject("data").getString("desc"));
                                            ExpressEntity.this.setState(4);
                                            mExpressEntityDao.update(ExpressEntity.this);
                                            listener.onFailure(ExpressEntity.this);
                                        }
                                    }
                                }
                                else if (ExpressEntity.this.getType() == 3) {
                                    EDOutputData edData = new EDOutputData();
                                    NativeEncryption.JNI_IDecrypt(data.getString("body"), edData);
                                    LogUtil.e(edData.GetData());

                                    JSONObject resObj = JSON.parseObject(edData.GetData());

                                    if (resObj.getJSONObject("dta").getString("st").equals("ok")) {
                                        ExpressEntity.this.setState_des("上传成功");
                                        ExpressEntity.this.setState(3);
                                        mExpressEntityDao.update(ExpressEntity.this);
                                        listener.onSuccess(ExpressEntity.this);
                                    } else {
                                        ExpressEntity.this.setState_des(resObj.getJSONObject("dta").getString("ermsg"));
                                        ExpressEntity.this.setState(4);
                                        mExpressEntityDao.update(ExpressEntity.this);
                                        listener.onFailure(ExpressEntity.this);
                                    }

                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                        }
                    });
        }
    }


    public void fetchCom() {
        ExpressEntity.this.setState_des("正在查询快递公司...");
        listener.onFetchCom(ExpressEntity.this);
        mAppComponent.getAssistantApi()
                .fetchCom(ExpressEntity.this.getExpress())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        ExpressEntity.this.setState_des("所属快递公司查询失败");
                        if (e.getMessage().contains("555")) {
                            ExpressEntity.this.setState_des("未找到单号对应的快递公司");
                        }
                        ExpressEntity.this.setState(4);
                        listener.onFailure(ExpressEntity.this);
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        try {
                            JSONObject resObj = JSONObject.parseObject(responseBody.string());
                            JSONArray dataAry = resObj.getJSONObject("showapi_res_body").getJSONArray("data");
                            if (dataAry.size() == 1) {
                                JSONObject expObj = dataAry.getJSONObject(0);
                                String expName = expObj.getString("expName");
                                if (expName.contains("圆通")) {
                                    ExpressEntity.this.setType(0);
                                    mExpressEntityDao.update(ExpressEntity.this);
                                    listener.onSuccess(ExpressEntity.this);
                                    upload();
                                } else if (expName.contains("中通")) {
                                    ExpressEntity.this.setType(1);
                                    mExpressEntityDao.update(ExpressEntity.this);
                                    listener.onSuccess(ExpressEntity.this);
                                    upload();
                                }

                                else if (expName.contains("申通")) {
                                    ExpressEntity.this.setType(2);
                                    mExpressEntityDao.update(ExpressEntity.this);
                                    listener.onSuccess(ExpressEntity.this);
                                    upload();
                                }
                                else if (expName.contains("韵达")) {
                                    ExpressEntity.this.setType(3);
                                    mExpressEntityDao.update(ExpressEntity.this);
                                    listener.onSuccess(ExpressEntity.this);
                                    upload();
                                }


                                else {
                                    ExpressEntity.this.setType(-1);
                                    ExpressEntity.this.setState_des( expName + ",暂时不支持");
                                    mExpressEntityDao.update(ExpressEntity.this);
                                    listener.onFailure(ExpressEntity.this);
                                }


                            } else {
                                ExpressEntity.this.setState_des("所属快递公司不明确,请手动选择。");
                                ExpressEntity.this.setState(4);
                                listener.onFailure(ExpressEntity.this);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                });
    }

    public int getExpress_type() {
        return this.express_type;
    }

    public void setExpress_type(int express_type) {
        this.express_type = express_type;
    }






}
